package com.changpei.search.service.impl;

import com.changpei.common.result.Result;
import com.changpei.common.utils.JsonUtil;
import com.changpei.core.feign.FileFeign;
import com.changpei.search.dao.FileIndexMapper;
import com.changpei.search.pojo.FileIndex;
import com.changpei.search.service.FileIndexService;
import com.changpei.search.utils.SearchUtil;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 * <p>Title: File</p>
 * <p>Description: File业务层接口实现类</p>
 * @author weibiao
 */
@Service
@Slf4j
public class FileIndexServiceImpl implements FileIndexService {

    @Autowired
    private FileFeign fileFeign;

    @Autowired
    private FileIndexMapper fileIndexMapper;

    @Override
    public void importData() {
        fileIndexMapper.saveAll(JsonUtil.jsonToList(fileFeign.findAll().getData(), FileIndex.class));
    }

    @Override
    public Page<FileIndex> search(FileIndex fileIndex, int pageNum, int pageSize) {
        return fileIndexMapper.search(SearchUtil.buildBasicQuery(fileIndex, pageNum, pageSize).build());
    }

    @Override
    public Result<String> save(FileIndex fileIndex) {
        try {
            fileIndexMapper.save(fileIndex);
            return Result.ok();
        } catch (Exception e) {
            log.warn("File数据新增ES库失败", e.getMessage());
            return Result.failed();
        }
    }

    @Override
    public Result<String> deleteAll() {
        try {
            fileIndexMapper.deleteAll();
            return Result.ok();
        } catch (Exception e) {
            log.warn("清空File - ES库失败", e.getMessage());
            return Result.failed();
        }
    }

    @Override
    public Result<String> update(FileIndex fileIndex) {
        try {
            fileIndexMapper.save(fileIndex);
            return Result.ok();
        } catch (Exception e) {
            log.warn("File数据更新ES库失败", e.getMessage());
            return Result.failed();
        }
    }

    @Override
    public Result<String> deleteById(Long id) {
        try {
            fileIndexMapper.deleteById(id);
            return Result.ok();
        } catch (Exception e) {
            log.warn("删除File - ES库失败", e.getMessage());
            return Result.failed();
        }
    }

    @Override
    public FileIndex findById(Long id) {
        return fileIndexMapper.findById(id).get();
    }

    @Override
    public List<FileIndex> findAll() {
        return Lists.newArrayList(fileIndexMapper.findAll());
    }
}
